﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using ControleRepresentante.Logic.Models;
using ControleRepresentante.Logic.Repositories;
using ControleRepresentante.Logic.Statistics;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using WebSite.Controllers;
using Attribute = ControleRepresentante.Logic.Models.Attribute;

namespace ControleRepresentante.UnitTests
{
    public static class TestScenarioAttributeHelper
    {
        public static void DeleteAttribute(this TestScenario testScenario, Guid id)
        {
            IAttributeRepository attributeRepository = testScenario.RepositoryProvider.GetRepository<IAttributeRepository>();
            StatisticsBase statistics;
            int countBefore = attributeRepository.GetModels(out statistics).Count();
            using (AttributeController attributeController = new AttributeController(testScenario.RepositoryProvider, testScenario.SessionConfiguration, testScenario.ControllerExtensionProvider))
            {
                attributeController.Delete(id);
                attributeController.Delete(id, null);
                Assert.AreEqual(countBefore - 1, attributeRepository.GetModels(out statistics).Count());
            }
        }

        public static Guid CreateAttribute(this TestScenario testScenario, AttributeType attributeType, string name)
        {
            IAttributeRepository attributeRepository = testScenario.RepositoryProvider.GetRepository<IAttributeRepository>();
            StatisticsBase statistics;
            int countBefore = attributeRepository.GetModels(out statistics).Count();
            using (AttributeController attributeController = new AttributeController(testScenario.RepositoryProvider, testScenario.SessionConfiguration, testScenario.ControllerExtensionProvider))
            {
                attributeController.Create();
                ActionResult actionResult = attributeController.Create(name, attributeType.ToString());
                IEnumerable<Attribute> attributes = attributeRepository.GetModels(out statistics);
                Assert.AreEqual(countBefore + 1, attributes.Count());
                Attribute addedAttribute = attributes.FirstOrDefault(x => x.Name == name);
                Assert.AreEqual(name, addedAttribute.Name);
                Assert.AreEqual(attributeType, addedAttribute.Type);
                Assert.IsInstanceOfType(actionResult, typeof(RedirectToRouteResult));
                RedirectToRouteResult redirectToRouteResult = (RedirectToRouteResult)actionResult;
                Assert.AreEqual("Details", redirectToRouteResult.RouteValues["action"]);
                Assert.AreEqual(addedAttribute.Id, redirectToRouteResult.RouteValues["id"]);
                return addedAttribute.Id;
            }
        }
    }
}